//
//  RecommendView.m
//  Mooker
//
//  Created by Jikui Peng on 12-7-17.
//  Copyright (c) 2012年 banma. All rights reserved.
//

#import "RecommendView.h"
#import "LolayGridView.h"
#import "RecommendCell.h"
#import "SourceManager.h"
#import "SourceView.h"
#import "MKEnvObserverCenterApplication.h"
#import <QuartzCore/QuartzCore.h>
#import "ItemViewController.h"

#define kPathMoveTimeInterval    2.0f
#define kSwitchTimeInterval      6.0f

#define kMaxRecommendNum       6
#define kMaxADRecommendNum     3

#define kFramePreView            CGRectMake(0, 0, self.myScrollView.bounds.size.width, self.myScrollView.bounds.size.height)
#define kFrameCurView            CGRectMake(self.myScrollView.bounds.size.width, 0, self.myScrollView.bounds.size.width, self.myScrollView.bounds.size.height)
#define kFrameNextView           CGRectMake(2*self.myScrollView.bounds.size.width, 0, self.myScrollView.bounds.size.width, self.myScrollView.bounds.size.height)

@interface RecommendView ()<UIScrollViewDelegate,RecommendCellDelegate,MKEnvObserverApplicationProtocol,CuzyManagerDelegate>{
    NSTimer    *_picSwitchTimer;
    NSTimer    *_animationTimer;
    
    BOOL       _isVisible;
    
    UIScrollView           *_myScrollView;
    RecommendCell          *_preView;
    RecommendCell          *_curView;
    RecommendCell          *_nextView;
    
}

@property (nonatomic, retain) UIView            *bottomView;
@property (nonatomic, retain) UILabel           *titleLabel;
@property (nonatomic, retain) UILabel           *pageLabel;

@property (nonatomic, retain) UIScrollView      *myScrollView;
@property (nonatomic, retain) RecommendCell     *preView;
@property (nonatomic, retain) RecommendCell     *curView;
@property (nonatomic, retain) RecommendCell     *nextView;

@property (nonatomic, assign) NSInteger         currentPage;
@property (nonatomic, retain) NSMutableArray    *recArray;

- (void)showRecommedInfoWithArticle:(NSObject *)object;
- (void)autoSwitchNextArticle;

- (void)forwardPage;
- (void)nextPage;

- (void)showRecommedInfo;

@end

@implementation RecommendView
@synthesize bottomView = _bottomView;
@synthesize titleLabel = _titleLabel;
@synthesize pageLabel = _pageLabel;
@synthesize currentPage = _currentPage;
@synthesize delegate = _delegate;

@synthesize myScrollView = _myScrollView;
@synthesize preView = _preView;
@synthesize curView = _curView;
@synthesize nextView = _nextView;

- (void)dealloc{
    MKRemoveApplicationObserver(self);
    _delegate = nil;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = COLOR_RGB(255.0f, 255.0f, 255.0f);
        self.clipsToBounds = YES;
        
        [self addSubview:self.myScrollView];
        [self addSubview:self.bottomView];
        [self loadData];
        UITapGestureRecognizer  *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                               action:@selector(showRecommedInfo)];
        tap.numberOfTapsRequired= 1;
        [self addGestureRecognizer:tap];
        
        MKAddApplicationObserver(self);
    }
    return self;
}


- (void)showDefaultInfo
{
    self.titleLabel.text = @"iTao爱淘";
}

- (void)autoSwitchNextArticle
{
    INVALIDATE_TIMER(_picSwitchTimer);
    if ([self.recArray count] <=1) {
        return;
    }
    [UIView animateWithDuration:0.5f
                     animations:^{
                         self.curView.frame = kFramePreView;
                         self.nextView.frame = kFrameCurView;
                     } completion:^(BOOL finished) {
                         [self nextPage];
                     }];
    
}

- (void)startAnimation
{
    _isVisible = YES;
    INVALIDATE_TIMER(_animationTimer);
    INVALIDATE_TIMER(_picSwitchTimer);
    
    [self.curView startAnimation];
}

- (void)stopAnimation
{
    _isVisible = NO;
    INVALIDATE_TIMER(_animationTimer);
    INVALIDATE_TIMER(_picSwitchTimer);
    [self.curView stopAnimation];
    
}

- (void)loadData{
    [[CuzyManager sharedManager] requstTBKItemsWithKeyWord:@"" WithThemeID:kSelectedThemID WithPicSizeType:PicSize360 WithSort:nil WithPageIndex:0 withDelegate:self];
}

- (void)showRecommedInfo{
    if (self.curView.object == nil){
        [self loadData];
        return;
    }
        
    
    CuzyTBKItem  *object = self.curView.object;
    ItemViewController *itemVC = [[ItemViewController alloc] initWithMeItem:object];
    itemVC.shareImage = self.curView.imageView.image;
    [[[DataEnvironment sharedDataEnvironment] navController] pushViewController:itemVC animated:YES];
}

#pragma mark - 推荐内容
- (void)showRecommedInfoWithArticle:(NSObject *)object
{
    NSString   *title = nil;
    if (object) {
        if ([object isKindOfClass:[CuzyTBKItem class]]) {
            CuzyTBKItem *recommendation = (CuzyTBKItem *)object;
            title = recommendation.itemName;
        }
        
    }
    
    if (title == nil || [title isEqualToString:@""]) {
        self.titleLabel.text = @"";
    }else{
        self.titleLabel.text = title;
    }
}

#pragma mark - RecommendCellDelegate
- (void)pathAnimationDidFinishedWithImageView:(UIImageView *)imageView
{
    if ([self.recArray count] > 1 && _isVisible) {
        INVALIDATE_TIMER(_picSwitchTimer);
        _picSwitchTimer = [NSTimer scheduledTimerWithTimeInterval:kSwitchTimeInterval
                                                            target:self
                                                          selector:@selector(autoSwitchNextArticle)
                                                          userInfo:nil
                                                           repeats:NO];
    }
}

- (void)startAnimationTimer{
    INVALIDATE_TIMER(_animationTimer);
    _animationTimer = [NSTimer scheduledTimerWithTimeInterval:kPathMoveTimeInterval
                                                        target:self
                                                      selector:@selector(startAnimation)
                                                      userInfo:nil
                                                       repeats:NO];
}

#pragma mark - UIScrollViewDelegate methods
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self stopAnimation];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //scrollview结束滚动时判断是否已经换页
	if (self.myScrollView.contentOffset.x > self.myScrollView.bounds.size.width) {
        [self nextPage];
        
	} else if (self.myScrollView.contentOffset.x < self.myScrollView.bounds.size.width) {
        [self forwardPage];
	}
    
}

- (void)resetRecommendData{
    if (self.curView.object) {
        [self showRecommedInfoWithArticle:self.curView.object];
    }else{
        [self showDefaultInfo];
    }
    
    //设置前一张图片
    NSInteger  prev = self.currentPage-1;
    if (prev < 0) {
        prev = [_recArray count]-1;
    }
    [self.preView setObject:[_recArray objectAtIndex:prev]];
    
    //设置后一张图片
    NSInteger  next = self.currentPage+1;
    if (next >= [_recArray count]) {
        next = 0;
    }
    
    [self.nextView setObject:[_recArray objectAtIndex:next]];
    
    [self startAnimationTimer];
}

- (void)forwardPage
{
    RecommendCell  *temp = nil;
    temp = self.curView;
    self.curView = self.preView;
    self.preView = self.nextView;
    self.nextView = temp;
    
    self.preView.frame = kFramePreView;
    self.curView.frame = kFrameCurView;
    self.nextView.frame = kFrameNextView;
    self.nextView.imageView.layer.position = CGPointMake(self.myScrollView.bounds.size.width/2, self.myScrollView.bounds.size.height/2);
    [self.myScrollView setContentOffset:CGPointMake(self.myScrollView.bounds.size.width, 0.0)];
    
    if (self.currentPage <= 0) {
        self.currentPage = [_recArray count]-1;
    }else{
        self.currentPage = self.currentPage-1;
    }
    
    [self resetRecommendData];
}

- (void)nextPage
{
    RecommendCell  *temp = nil;
    temp = self.curView;
    self.curView = self.nextView;
    self.nextView = self.preView;
    self.preView = temp;
    
    self.preView.frame = kFramePreView;
    self.curView.frame = kFrameCurView;
    self.nextView.frame = kFrameNextView;
    
    self.preView.imageView.layer.position = CGPointMake(self.myScrollView.bounds.size.width/2, self.myScrollView.bounds.size.height/2);
    [self.myScrollView setContentOffset:CGPointMake(self.myScrollView.bounds.size.width, 0.0)];
    
    if (self.currentPage >= [_recArray count]-1) {
        self.currentPage = 0;
    }else{
        self.currentPage = self.currentPage+1;
    }
    
    [self resetRecommendData];
}

#pragma mark - MKEnvObserverApplicationProtocol
- (void)mkEnvObserverApplicationWillEnterForeground:(NSNotification *)notification
{
    if ([(SourceView *)self.delegate isSourceViewShown] && [self.recArray count]>1){
        [self performSelector:@selector(autoSwitchNextArticle) withObject:nil afterDelay:0.5f];
    }
    [self loadData];
}

- (void)mkEnvObserverApplicationDidEnterBackground:(NSNotification *)notification
{
    if ([(SourceView *)self.delegate isSourceViewShown] && [self.recArray count]>0){
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        [self stopAnimation];
    }
}

#pragma mark DataManagerDelegate
-(void) updateViewForSuccess:(id)dataModel{
    if (dataModel == nil) {
        return;
    }
    NSMutableArray *items = nil;
    
    if ([(NSArray*)dataModel count] >= 6) {
        NSArray *array = [dataModel objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 6)]];
        items = [[NSMutableArray alloc] initWithArray:array];
    }else{
        items = [[NSMutableArray alloc] initWithArray:dataModel];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self setRecArray:items];
    });
    
}
-(void) updateViewForError:(NSError *)errorInfo{

}
#pragma mark - setter Method
- (void)setRecArray:(NSMutableArray *)recArray{
    if (_recArray != recArray) {
        BOOL  needRefresh = YES;
        _recArray = [NSMutableArray arrayWithArray:recArray];
        
        //数据更改时，设置ScrollView的contentSize
        if ([_recArray count] <= 1) {
            self.myScrollView.contentSize = CGSizeMake(self.myScrollView.bounds.size.width,
                                                       self.myScrollView.bounds.size.height);
        }else{
            self.myScrollView.contentSize = CGSizeMake(3*self.myScrollView.bounds.size.width,
                                                       self.myScrollView.bounds.size.height);
        }
        
        if ([_recArray count] >0 && needRefresh) {
            //cancel previous perform requests
            [NSObject cancelPreviousPerformRequestsWithTarget:self
                                                     selector:@selector(autoSwitchNextArticle)
                                                       object:nil];
            
            self.currentPage = 0;
            [self.curView setObject:[_recArray objectAtIndex:0]];
            
            if ([_recArray count] > 1) {
                self.preView.frame = kFramePreView;
                self.curView.frame = kFrameCurView;
                self.nextView.frame = kFrameNextView;
                self.myScrollView.contentOffset = CGPointMake(self.myScrollView.bounds.size.width, 0);
            }
            
            if ([_recArray count] > 1) {  //推荐位多数据
                CuzyTBKItem *preObj = nil;
                CuzyTBKItem *nextObj = nil;
                if (self.currentPage <= 0) {
                    preObj = [_recArray lastObject];
                    nextObj = [_recArray objectAtIndex:self.currentPage+1];
                }else if(self.currentPage >= [_recArray count]-1){
                    self.currentPage = [_recArray count]-1;
                    preObj = [_recArray objectAtIndex:self.currentPage - 1];
                    nextObj = [_recArray objectAtIndex:0];
                }else{
                    preObj = [_recArray objectAtIndex:self.currentPage-1];
                    nextObj = [_recArray objectAtIndex:self.currentPage + 1];
                }
                [self.preView setObject:preObj];
                [self.nextView setObject:nextObj];
            }else if ([_recArray count] == 1) {    //推荐位只有单个数据时
                self.curView.frame = kFramePreView;
                self.myScrollView.contentOffset = CGPointMake(0, 0);
            }
            
            [self showRecommedInfoWithArticle:self.curView.object];
            [self setCurrentPage:self.currentPage];
        }
    }

}

- (void)setCurrentPage:(NSInteger)currentPage{
    _currentPage = currentPage;
    
    if ([self.recArray count] == 0) {
        self.pageLabel.hidden = YES;
    }else{
        self.pageLabel.hidden = NO;
        self.pageLabel.text = [NSString stringWithFormat:@"%d/%d",_currentPage+1,[self.recArray count]];
    }
}

#pragma mark - getter
- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(3, self.bounds.size.height-53, self.myScrollView.bounds.size.width, 50)];
        _bottomView.contentMode = UIViewContentModeScaleAspectFill;
        _bottomView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _bottomView.backgroundColor = COLOR_RGBA(0.0, 0.0, 0.0, 0.6);
        
        UIImage *img = IMGFROMBUNDLE(@"bg_recommend_page.png");
        UIImageView  *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(2, floorf((50-img.size.height)/2), img.size.width, img.size.width)];
        imgView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
        imgView.backgroundColor = [UIColor clearColor];
        imgView.image = img;
        [_bottomView addSubview:imgView];
        
        self.pageLabel.frame = imgView.frame;
        [_bottomView addSubview:self.pageLabel];
        
        self.titleLabel.frame = CGRectMake(img.size.width+4, 5, self.myScrollView.bounds.size.width-img.size.width-10, 40);
        [_bottomView addSubview:self.titleLabel];
        
        [self addSubview:_bottomView];
    }
    return _bottomView;
}

- (UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(56, 3, self.bounds.size.width-60, 40)];
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.font = FONT_CONTENT(14.0f);
        _titleLabel.textColor = COLOR_RGB(255.0,255.0,255.0);
        _titleLabel.textAlignment = [Util getAlign:ALIGNTYPE_LEFT];
        _titleLabel.numberOfLines = 0;
    }
    return _titleLabel;
}

- (UILabel *)pageLabel{
    if (!_pageLabel) {
        _pageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, 56, 40)];
        _pageLabel.backgroundColor = [UIColor clearColor];
        _pageLabel.textAlignment = [Util getAlign:ALIGNTYPE_CENTER];
        _pageLabel.font = FONT_NUMBER(23.0f);
        _pageLabel.textColor = COLOR_RGB(255.0,255.0,255.0);
    }
    return _pageLabel;
}

- (UIScrollView *)myScrollView {
    if (!_myScrollView) {
        _myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(3, 3, self.bounds.size.width-6, self.bounds.size.height-6)];
        _myScrollView.delegate = self;
        _myScrollView.bounces = NO;
        _myScrollView.pagingEnabled = YES;
        _myScrollView.backgroundColor = [UIColor clearColor];
        _myScrollView.showsHorizontalScrollIndicator = NO;
        _myScrollView.showsVerticalScrollIndicator = NO;
        [_myScrollView addSubview:self.preView];
        [_myScrollView addSubview:self.curView];
        [_myScrollView addSubview:self.nextView];
    }
    return _myScrollView;
}

- (RecommendCell *)preView{
    if (!_preView) {
        _preView = [[RecommendCell alloc] initWithFrame:kFramePreView];
        _preView.clipsToBounds = YES;
        _preView.delegate = self;
        _preView.contentMode = UIViewContentModeScaleAspectFill;
        _preView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _preView.userInteractionEnabled = YES;
    }
    return _preView;
}
- (RecommendCell *)curView{
    if (!_curView) {
        _curView = [[RecommendCell alloc] initWithFrame:kFrameCurView];
        _curView.clipsToBounds = YES;
        _curView.delegate = self;
        _curView.contentMode = UIViewContentModeScaleAspectFill;
        _curView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _curView.userInteractionEnabled = YES;
    }
    return _curView;
}
- (RecommendCell *)nextView{
    if (!_nextView) {
        _nextView = [[RecommendCell alloc] initWithFrame:kFrameNextView];
        _nextView.clipsToBounds = YES;
        _nextView.delegate = self;
        _nextView.contentMode = UIViewContentModeScaleAspectFill;
        _nextView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _nextView.userInteractionEnabled = YES;
    }
    return _nextView;
}


@end


